/*
 * Copyright 2014 Matyas Mazzag
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *   http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package org.mcubed.soapui


import org.apache.log4j.Logger
import org.codehaus.groovy.control.CompilerConfiguration

import com.eviware.soapui.model.testsuite.TestCaseRunner


/**
 * New and improved ScriptRunner class that can be called to run a Groovy script.
 * <br />
 * The script is expected to reside on the filesystem relative to the directory specified
 * by the TestSuite property 'scripts.dir' or environment variable EGL.i_SCRIPTS.
 *
 * @author Matyas Mazzag
 *
 */
class ScriptRunner {
	
	/**
	 * This constructor provides a way of running Groovy scripts from SoapUI.
	 * <br />
	 * Classes need to implement a run() method without any arguments (as dictated by the
	 * {@link groovy.lang.Script} abstract class.  Both scripts and class files need to end with
	 * extension '.groovy'
	 * <br />
	 * The script files don't need to have been compiled and can be absolute files names.
	 * If they are not absolute files a variable called scripts.dir needed to be set on
	 * TestSuite containing the TestCase (that runs this Groovy code step) OR an environment
	 * variable called SOAPUI_SCRITPS needs to be defined pointing to the root directory where
	 * the scripts are to be loaded from.
	 * <br />
	 * Scripts will always have {@link org.mcubed.soapui.BaseScript} set as
	 * their base class.
	 * <br />
	 * Before running the scripts {@link org.mcubed.soapui.BaseScript#init()} is called.
	 * <br />
	 * Every script has variables log, testCase and context available to them as they would be
	 * when run inside SoapUI.
	 *
	 * @param scriptFilePath
	 * @param closure
	 * @param args
	 * @throws Exception
	 */
	ScriptRunner( String scriptFilePath, Closure closure = null, Map<String, Object>... args ) throws Exception {
		TestCaseRunner testRunner = null
		// Create bindings for extra args so that they can be accessed from the scripts:
		Binding binding = new Binding()
		args?.each {
			it.each { key, value ->
				binding.setVariable( key, value )
				if( 'testRunner' == key ) {
					testRunner = value
				}
			}
		}
		
		// Set baseclass for all scripts:
		CompilerConfiguration compiler = new CompilerConfiguration()
		//TODO: should this be configurable ???
		compiler.scriptBaseClass = 'org.mcubed.soapui.BaseScript'

		// Figure out the script on the filesystem:
		scriptFilePath = scriptFilePath.replaceFirst( /(?i)\.groovy$/, '' ).replaceAll( /\./, '/' ) + '.groovy'

		// Setup Groovy classloader:
		GroovyClassLoader loader = new GroovyClassLoader( getClass().classLoader )
		if( !new File( scriptFilePath ).absolute ) {
			loader.addClasspath( new ScriptFilePathResolver( testRunner ).resolve().canonicalPath )
		}

		// Startup Groovy shell:
		GroovyShell shell = new GroovyShell( loader, binding, compiler )
		// Load script:
		GroovyObject script = shell.parse( new ScriptFilePathResolver( testRunner ).resolve( scriptFilePath ))
		
		// Call init():
		script.invokeMethod( 'init', null )

		// Finally run that script:
		script.run()
	}

}
